package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect//注解:表示这个类是一个切面类AOP
@Component
public class OperateLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.anno.Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());//登录用户id
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        operateLog.setClassName(pjp.getTarget().getClass().getName());//类名称
        operateLog.setMethodName(pjp.getSignature().getName());//方法名称
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//方法参数

        //调用原始方法运行
        long start=System.currentTimeMillis();

        Object result = pjp.proceed();

        long end=System.currentTimeMillis();

        operateLog.setReturnValue(result.toString());//返回值
        operateLog.setCostTime(end-start);//耗时

        //保存操作日志
        operateLogMapper.insert(operateLog);
        return result;
    }
}
